package com.zxw.spring.bean.自定义bean;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author Xuewei.Zhang
 * @date 2023/7/23
 */
public class CustomBeanDemo {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(User.class);
        beanDefinitionBuilder.addPropertyValue("name", "張峻霖");
        beanDefinitionBuilder.addPropertyValue("age", 18);

        // 自定义Bean注入上下文方式1
        applicationContext.registerBeanDefinition("ZJL", beanDefinitionBuilder.getBeanDefinition());
        // 自定义Bean注入上下文方式2
        BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinitionBuilder.getBeanDefinition(),applicationContext);

        // 启动上下文
        applicationContext.refresh();
        System.out.println(applicationContext.getBeansOfType(User.class));
        // 关闭上下文
        applicationContext.close();
    }
}
